package controllers

import (
	"encoding/json"
	"errors"
	//"strconv"
	"gitee.com/lzqysoft/ims/models"
	"strings"

	"github.com/astaxie/beego"
	"gitee.com/lzqysoft/ims/libs/encrypt"
	"time"
)

// BuyController operations for Buy
type BuyController struct {
	CommonController
}

// URLMapping ...
func (c *BuyController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("BuyApply", c.BuyApply)
	c.Mapping("GetMyBuy", c.GetMyBuy)

}

// Ord 订单前端json数据
type bu struct {
	Id            string            `json:"Id"`
	Cname         string            `json:"CustName"`
	CustId        string            `json:"CustId"`
	DiscountPrice float64           `json:"DiscountPrice"`
	Name          string            `json:"Name"`
	Off           float64           `json:"Off"`
	Price         float64           `json:"Price"`
	Remark        string            `json:"Remark"`
	Sales         []*models.BuyItem `json:"Sales"`
	Receiv        []*models.PayItem `json:"Receiv"`
}

// Post ...
// @Title Post
// @Description create Buy
// @Param	body		body 	models.Buy	true		"body for Buy content"
// @Success 201 {int} models.Buy
// @Failure 403 body is empty
// @router / [post]
func (c *BuyController) Post() {
	var v models.Buy
	var p bu
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrNoData)
	}
	err = json.Unmarshal(rdata, &p)
	v.Name = p.Name
	v.PartId = p.CustId
	v.PartName = p.Cname
	v.UserId = user.Id
	v.Price = p.Price
	//v.DiscountPrice = p.DiscountPrice
	//v.Off = p.Off
	v.Remark = p.Remark
	v.Isdelete = 0
	v.Status = 1
	v.Creater = user.Abbr
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Id = encrypt.GetGuid()
	_, err = models.AddBuy(&v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)
	}
	for _, s := range p.Sales {
		s.Id = encrypt.GetGuid()
		s.BuyId = v.Id
		s.Creater = user.Abbr
		s.Ctime = v.Ctime
		s.Updater = v.Updater
		s.Utime = v.Utime
		_, err = models.AddBuyItem(s)
	}
	beego.Debug(p.Receiv)
	err = models.AddPayByRecive(p.Receiv, v.Id, c.User.Abbr)
	if err != nil {
		//c.RetSuccess("收款单添加失败")
		beego.Debug(err)
	}
	beego.Debug("添加了付款单，单未启用！")
	c.Dlog("添加了采购订单", v.Id)
	c.RetSuccess(v.Id)
}

// GetOne ...
// @Title Get One
// @Description get Buy by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Buy
// @Failure 403 :id is empty
// @router /:id [get]
func (c *BuyController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	v, err := models.GetBuyById(idStr)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get Buy
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Buy
// @Failure 403
// @router / [get]
func (c *BuyController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllBuy(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)

	}
	c.RetSuccess(l)
}

// Put ...
// @Title Put
// @Description update the Buy
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Buy	true		"body for Buy content"
// @Success 200 {object} models.Buy
// @Failure 403 :id is not int
// @router /:id [put]
func (c *BuyController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	v := models.Buy{Id: idStr}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateBuyById(&v); err == nil {
			c.Data["json"] = "OK"
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// Delete ...
// @Title Delete
// @Description delete the Buy
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *BuyController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	if err := models.DeleteBuy(idStr); err == nil {
		c.Data["json"] = "OK"
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// BuyApply ...
// @Title BuyApply
// @Description 申请上报
// @Param	body		body 	models.Buy	true		"body for Assetsbuy content"
// @Success 201 {int} models.Buy
// @Failure 403 body is empty
// @router /BuyApply [post]
func (c *BuyController) BuyApply() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		busyid := value.(string)
		flow, err := models.GetFlowByName("采购订单")
		fins, err := models.InitFSM(user, flow.Id, "yjk_buy", busyid)
		beego.Debug("fins err: ", fins)
		fsm := models.GetFSM(fins)
		// // beego.Debug("fsm err: ", fsm)
		ev, _ := models.GetEventByName("上报")
		err = fsm.Trigger(fins.Currentstate, ev.Id, fins)
		if err != nil {
			beego.Error("trigger1 err: ", err)
		}
		c.Dlog("上报采购订单", busyid)
	}

	// ts, err := models.GetFlowinstanceByBusyId(busyid)
	// // 针对退回的单据重新生成流程实例
	// if ts.Status == 3 {
	// 	models.ReApply(user.Id, busyid, ts)
	// 	flow, _ := models.GetFlowByName("采购单")
	// 	ts, _ = models.InitFSM(user, flow.Id, "Assetsbuy", busyid)
	// }
	// beego.Debug("ts err: ", ts)
	// fsm := models.GetFSM(ts)
	// // beego.Debug("fsm err: ", fsm)
	// ev, _ := models.GetEventByName("上报")
	// err = fsm.Trigger(ts.Currentstate, ev.Id, ts)
	// if err != nil {
	// 	beego.Error("trigger err: ", err)
	// 	c.RetError(ErrPermission)
	// }

	c.RetSuccess(sdata)

}

// GetMyBuy ...
// @Title Get All
// @Description 获取我的未开是的采购订单
// @Success 200 {object} models.Buy
// @Failure 403
// @router /GetMyBuy [get]
func (c *BuyController) GetMyBuy() {
	user := c.User
	if ml, err := models.GetBuyByUserAndStatus(user.Id, 1); err == nil {
		c.RetSuccess(ml)
	} else {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}

}
